//
//  SeekMachineViewController.m
//  SmartCup
//
//  Created by Kendama on 2017/5/19.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "SeekMachineViewController.h"
#import "MatchMachineTableViewCell.h"
#import "DTCDeviceModel.h"

@interface SeekMachineViewController ()<UITableViewDelegate,UITableViewDataSource>

/** 搜索背景图 **/
@property(nonatomic,strong) UIImageView *searchBackgroundView;
@property(nonatomic,strong) UIImageView *searchIcon;

/** 提示 **/
@property(nonatomic,strong) UILabel *tipsLabel;
@property(nonatomic,strong) UILabel *bottomTipsLabel;


/** 设备状态 **/
@property(nonatomic,strong) MachineView *machineView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *searchView;

@property(nonatomic, strong) NSMutableArray *deviceList ;

/** 背景图 **/
@property(nonatomic,strong) UIImageView *backbroundView;
@property(nonatomic,strong) UILabel *noTipsLabel;
@property(nonatomic,strong) UIView *noMachineView;
/** 重新扫描按钮 **/
@property(nonatomic,strong) UIButton *repeatButton;

@end

@implementation SeekMachineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)refreshBaseControlValue {
    
    [self setLeftButtonImage:[UIImage imageNamed:@"nav_icon_back"]];
    [self setNavigationTitle:@"搜索设备" titleColor:[UIColor whiteColor]];
    self.navigationBar.backgroundColor = [UIColor colorWithHexString:@"3E76F6"];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F9"];
    
    [self layoutSubviews];
    
    [self scanDeviceList];
    
    
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"matchMachine" object:nil];
    
    


}

#pragma mark -- 事件
- (void)notification:(NSNotification *)dic{
    if ([dic.userInfo[@"blueConnect"] isEqualToString:@"YES"]) {
//        [SVProgressHUD showSuccessWithStatus:@"配对成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    if ([dic.userInfo[@"blueList"] isEqualToString:@"YES"]) {
        [self.deviceList removeAllObjects];
        [_deviceList addObjectsFromArray:[[DTCBluetoothManager shareInstance]scanDeviceList]];
        if (_deviceList.count > 0) {
            [self.view bringSubviewToFront:self.tableView];
            [self.tableView reloadData];
        } else {
            [self.view bringSubviewToFront:self.searchView];
        }
    }
    
    if ([dic.userInfo[@"blueFail"] isEqualToString:@"YES"]) {
        [SVProgressHUD showSuccessWithStatus:@"配对失败"];
    }
}


- (void)scanDeviceList {
    NSLog(@"蓝牙中心状态：%ld",(long)[[DTCBluetoothManager shareInstance]blueState]);
    if ([[DTCBluetoothManager shareInstance]blueState] == 4) {
        UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:@"蓝牙未打开" message:@"请打开蓝牙" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alterView show];
    } else {
        
    }
    [self.searchIcon.layer addAnimation:[self moveX:1.f X:[NSNumber numberWithFloat:px1080Width(300)]] forKey:nil];

    
    [self.deviceList removeAllObjects];
    [_deviceList addObjectsFromArray:[[DTCBluetoothManager shareInstance]scanDeviceList]];
    
//    NSLog(@"周边蓝牙设备%@",self.deviceList);
//    [DTCBluetoothManager shareInstance].delegate = self;
    if (_deviceList.count > 0) {
        [self.view bringSubviewToFront:self.tableView];
        [self.tableView reloadData];
    } else {
        [self.view bringSubviewToFront:self.searchView];
    }
    
    [self performSelector:@selector(delayMethod) withObject:nil afterDelay:10.0]; //延时10秒检查是否有扫描到设备
}


- (void)delayMethod{
    if (_deviceList.count == 0) {
        [self.view bringSubviewToFront:self.noMachineView];
        [self.searchIcon.layer removeAllAnimations];
    }
}

- (void) layoutSubviews {
    __weak UIView *superView = self.view;

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.width.mas_equalTo(superView);
        make.bottom.equalTo(superView);
    }];
    
//    self.tableView.hidden = YES;
    
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.width.mas_equalTo(superView);
        make.bottom.equalTo(superView);
    }];
    
    
    [self.searchBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.top.mas_equalTo(superView.mas_top).with.offset(px1920Height(272));
        make.height.width.mas_equalTo(px1080Width(456));
    }];
    
    [self.tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.searchBackgroundView.mas_bottom).with.offset(px1920Height(40));
        make.width.mas_equalTo(superView);
        make.height.mas_equalTo(px1920Height(73));
    }];
    
    [self.searchIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.searchBackgroundView.mas_top).with.offset(px1920Height(160));
        make.width.height.mas_equalTo(px1080Width(195));
        make.left.mas_equalTo(self.searchBackgroundView.mas_left).with.offset(px1080Width(0));
    }];
    
    [self.bottomTipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(superView.mas_bottom).with.offset(-px1920Height(162));
        make.left.mas_equalTo(superView).with.offset(px1080Width(107));
        make.right.mas_equalTo(superView).with.offset(-px1080Width(107));
        make.height.mas_equalTo(px1920Height(118));
    }];
    
    
    
    [self.noMachineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.width.mas_equalTo(superView);
        make.bottom.mas_equalTo(superView.mas_bottom);
    }];

    [self.backbroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(px1920Height(272));
        make.centerX.mas_equalTo(superView.mas_centerX);
        make.width.mas_equalTo(px1080Width(456));
        make.height.mas_equalTo(px1920Height(456));
    }];
    
    [self.noTipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.backbroundView.mas_bottom).with.offset(px1920Height(40));
        make.width.mas_equalTo(superView);
        make.height.mas_equalTo(px1920Height(73));
    }];
    
    
    [self.repeatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.noTipsLabel.mas_bottom).with.offset(px1920Height(139));
        make.left.mas_equalTo(superView).with.offset(px1080Width(45));
        make.right.mas_equalTo(superView).with.offset(-px1080Width(45));
        make.height.mas_equalTo(px1920Height(148));
    }];
}


- (void)onRightButtonClick:(id)sender {
    __weak UIView *superView = self.view;
    [self.machineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.width.mas_equalTo(superView);
        make.height.mas_equalTo(px1920Height(740));
    }];
    
    [self setRightButtonTitle:@"完成配对"];
}

-(CABasicAnimation *)moveX:(float)time X:(NSNumber *)x{
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];///.y的话就向下移动。
    animation.toValue = x;
    animation.duration = time;
    animation.removedOnCompletion = YES;//yes的话，又返回原位置了。
    animation.repeatCount = MAXFLOAT;
    animation.fillMode = kCAFillModeForwards;
    return animation;
    
}


#pragma mark -- 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //    NSArray *array = self.listArray[section];
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _deviceList.count;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return px1920Height(200);
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 0.01;
//
//}

//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return px1920Height(40);
//    return 0.01;
//}

//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"device_backImage"]];
//    return imageView;
//}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MatchMachineTableViewCell *cell = [MatchMachineTableViewCell cellWithTableView:tableView];
    DTCDeviceModel *model = _deviceList[indexPath.section];
    cell.device = model;
    cell.matchBlock = ^{
        [[DTCBluetoothManager shareInstance]disconnectDevice:model];
        [[DTCReConnectBlueManager sharedInstance]startReconnectDevice:model];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //    cell.textLabel.text = self.listArray[indexPath.section][indexPath.row];
    //    cell.textLabel.textColor = [UIColor darkGrayColor];
    //    cell.textLabel.font = [UIFont systemFontOfSize:15];
    
    //    cell.imageView.image = [UIImage imageNamed:self.imageListArray[indexPath.section][indexPath.row]];
    //    cell.imageView.image =
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DTCDeviceModel *model = _deviceList[indexPath.row];
    
    [[DTCBluetoothManager shareInstance]disconnectDevice:model];
    [[DTCReConnectBlueManager sharedInstance]startReconnectDevice:model];
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}






#pragma mark -- 懒加载
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [superView addSubview:_tableView];
    }
    return _tableView;
}

- (UIImageView *)searchBackgroundView
{
    if(!_searchBackgroundView)
    {
        __weak UIView *superView = self.searchView;
        _searchBackgroundView = [[UIImageView alloc]init];
        [superView addSubview:_searchBackgroundView];
        _searchBackgroundView.image = [UIImage imageNamed:@"bg_search"];
    }
    return _searchBackgroundView;
}

- (UIImageView *)searchIcon
{
    if(!_searchIcon)
    {
        __weak UIView *superView = self.searchBackgroundView;
        _searchIcon = [[UIImageView alloc]init];
        [superView addSubview:_searchIcon];
        _searchIcon.image = [UIImage imageNamed:@"放大镜"];
    }
    return _searchIcon;
}


- (UILabel *)tipsLabel
{
    if(!_tipsLabel)
    {
        __weak UIView *superView = self.searchView;
        _tipsLabel = [[UILabel alloc]init];
        [superView addSubview:_tipsLabel];
        [_tipsLabel setFont:[UIFont systemFontOfSize:px1080Width(52)]];
        [_tipsLabel setTextColor:[UIColor colorWithHexString:@"#585D6D"]];
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
        _tipsLabel.text = @"正在搜索您的【一杯子】...";
    }
    return _tipsLabel;
}

- (UILabel *)bottomTipsLabel
{
    if(!_bottomTipsLabel)
    {
        UIView *superView = self.searchView;
        _bottomTipsLabel = [[UILabel alloc]init];
        [superView addSubview:_bottomTipsLabel];
        _bottomTipsLabel.numberOfLines = 0;
        _bottomTipsLabel.textAlignment = NSTextAlignmentCenter;
        [_bottomTipsLabel setFont:[UIFont systemFontOfSize:px1080Width(42)]];
        [_bottomTipsLabel setTextColor:[UIColor colorWithHexString:@"#585D6D"]];
        _bottomTipsLabel.text = @"请确保手机蓝牙开启，并确保\n手机和【一杯子】处于合适的距离（5米以内）";
    }
    return _bottomTipsLabel;
}


- (MachineView *)machineView
{
    if(!_machineView)
    {
        __weak UIView *superView = self.view;
        _machineView = [[MachineView alloc]init];
        [superView addSubview:_machineView];
    }
    return _machineView;
}

- (UIView *)searchView
{
    if(!_searchView)
    {
        UIView *superView = self.view;
        _searchView = [[UIView alloc]init];
        _searchView.backgroundColor = [UIColor whiteColor];
        [superView addSubview:_searchView];
    }
    return _searchView;
}

- (NSMutableArray *)deviceList
{
    if(!_deviceList)
    {
        _deviceList = [[NSMutableArray alloc]init];
    }
    return _deviceList;
}

- (UILabel *)noTipsLabel
{
    if(!_noTipsLabel)
    {
        UIView *superView = self.noMachineView;
        _noTipsLabel = [[UILabel alloc]init];
        [superView addSubview:_noTipsLabel];
        [_noTipsLabel setFont:[UIFont systemFontOfSize:px1080Width(52)]];
        [_noTipsLabel setTextColor:[UIColor colorWithHexString:@"#585D6D"]];
        _noTipsLabel.textAlignment = NSTextAlignmentCenter;
        _noTipsLabel.text = @"没有搜索到设备";
    }
    return _noTipsLabel;
}

- (UIImageView *)backbroundView
{
    if(!_backbroundView)
    {
        UIView *superView = self.noMachineView;
        _backbroundView = [[UIImageView alloc]init];
        [superView addSubview:_backbroundView];
        _backbroundView.image = [UIImage imageNamed:@"bg_equipment"];
    }
    return _backbroundView;
}

- (UIView *)noMachineView
{
    if(!_noMachineView)
    {
        UIView *superView = self.view;
        _noMachineView = [[UIView alloc]init];
        _noMachineView.backgroundColor = [UIColor whiteColor];
        [superView addSubview:_noMachineView];
    }
    return _noMachineView;
}


- (UIButton *)repeatButton
{
    if(!_repeatButton)
    {
        UIView *superView = self.noMachineView;
        _repeatButton = [[UIButton alloc]init];
        [superView addSubview:_repeatButton];
        [_repeatButton setTitle:@"重新搜索" forState:UIControlStateNormal];
        [_repeatButton setBackgroundImage:[UIImage imageNamed:@"button_login_nor"] forState:UIControlStateNormal];
        [_repeatButton setBackgroundImage:[UIImage imageNamed:@"button_login_sel"] forState:UIControlStateSelected];
        [_repeatButton addTarget:self action:@selector(scanDeviceList) forControlEvents:UIControlEventTouchUpInside];
        [_repeatButton.titleLabel setFont:[UIFont systemFontOfSize:px1080Width(52)]];
    }
    return _repeatButton;
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"matchMachine" object:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
